import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, setUser,getUser,removeUser } from '@/utils/auth'
import {getUserData } from '@/api/user/index'
import { defineStore } from 'pinia';
import {getRouters } from '@/api/user/index' 
import { getCity,getCountry } from '@/api/system/city'
import { generateKeyPair, getAesKey, rsaEncrypt, rsaDecrypt,aesEncrypt,aesDecrypt } from "@/tools/encryptionAndDecryption";
import Cookies from 'js-cookie'
const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      userType: '',
       
    }),
    actions: {
      // 登录
      login (userInfo: { username: string; password: any }) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        return new Promise<void>((resolve, reject) => { 
          setToken("Basic bWFsbC1hZG1pbjoxMjM0NTY=")
          login(username, password).then((res: { token: any }) => {
            if(res.code == "00000"){
              const { publicKey , privateKey } = generateKeyPair()
              getAesKey({publicKey:publicKey}).then((res: any) => { 
                if(res.code == "00000"){
                    const decryptInfo = {
                      secretKey:res.data.secretKey,
                      secretIv:res.data.secretIv,
                      privateKey:privateKey
                    }
                    Cookies.set("decryptInfo",JSON.stringify(decryptInfo))
                }
              }).catch((error: any) => { 
                console.log("ERROR",error)
              })
              setToken(res.data.access_token)
              getCity({}).then((res: any) => {
                localStorage.setItem('cityList', JSON.stringify(res.data))
              })
              getCountry({}).then((res: any) => {
                localStorage.setItem('countryList', JSON.stringify(res.data))
              })
              
              this.token = res.data.access_token
              getUserData(res.data.userId).then((resp: any) => {
                setUser(resp.data)
              })
              getRouters(res.data.userId).then((res) => { 
                  localStorage.setItem('userRouters', JSON.stringify(res.data))
                  resolve()
              })
            }else{
              reject(res.msg)
            }
          }).catch((error: any) => {
            reject(error)
          })
        })
      },
     
      getUser() {
        let user = getUser()
        return JSON.parse(user)
      },
      // 获取用户信息
      getInfo () {
        return new Promise((resolve, reject) => {
          this.roles = ['ROLE_DEFAULT']
          resolve(1) 
        })
      },
      // 退出系统
      logOut () {
        return new Promise((resolve, reject) => {
          this.token = ''
          this.roles = []
          this.permissions=[]
          removeUser()
          removeToken()
          removeUser()
          resolve()

        })
      },
        
    }
  })

export default useUserStore
